package tag.auth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import core.util.StringUtil;

public class AuthTag extends BodyTagSupport {

	private static final long serialVersionUID = 9205701557019346900L;

	// 多个url地址可用;隔开
	private String url;

	// 是有权限显示内容还是无权限显示
	private String hasRight;

	// 多个url之间的关系or/and
	private String relation;

	private String[] urls;

//	private AuthFilter authFilter;
//	{
//		authFilter = (AuthFilter) AppContextCollector.getContext("mainContext").getBean("authFilter");
//	}

	public AuthTag() {
		super();
	}

	public int doAfterBody() {
		try {
			BodyContent body = getBodyContent();
			String content = body.getString();

			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

			Boolean beHasRight = null;

			if (urls != null && urls.length > 0) {
				int iSize = urls.length;
				for (int i = 0; i < iSize; i++) {
					String vUrl = urls[i];
					boolean right = true; //authFilter.hasRightView(vUrl, request);
					if (getRelation().equalsIgnoreCase("or")) { // 如果权限关系是or，
																// 则一个有权限即返回
						if (right) {
							beHasRight = true;
							break;
						} else {
							beHasRight = false;
						}
					} else { // 如果权限关系是and, 则一个无权限既返回
						if (!right) {
							beHasRight = false;
							break;
						} else {
							beHasRight = true;
						}
					}

				}
			}

			if (beHasRight == Boolean.valueOf(this.getHasRight())) {
				body.getEnclosingWriter().print(content); // 输出过滤后的文本
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return (SKIP_BODY); // 终止jsp正文处理

	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;

		if (url == null || url.trim().equals("")) {
			return;
		}

		this.urls = StringUtil.split(url, ";");
	}

	public String getHasRight() {
		return (this.hasRight == null || !this.hasRight.equalsIgnoreCase("false")) ? "true" : "false";
	}

	public void setHasRight(String hasRight) {
		this.hasRight = hasRight;
	}

	public String getRelation() {
		return relation == null ? "or" : this.relation;
	}

	public void setRelation(String relation) {
		this.relation = relation;
	}

}
